package com.example.royalchef.fragment;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.royalchef.R;
import com.example.royalchef.base.BaseFragment;
import com.example.royalchef.bean.LoginMessage;
import com.example.royalchef.utils.PreferUtils;
import com.example.royalchef.utils.UIUtils;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * author: Administrator
 * created on: 2017/6/27 9:44
 * description:
 */

public class SettingFragment extends BaseFragment {
    @BindView(R.id.iv_setting_item_avatar)
    ImageView ivAvatar;
    @BindView(R.id.tv_setting_item_avatar)
    TextView tvName;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = View.inflate(getContext(), R.layout.fragment_setting, null);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this, inflate);
        init();
        return inflate;
    }

    private void init() {
        String name = PreferUtils.getString("name", "");
        String avatar = PreferUtils.getString("avatar", "");
        if (TextUtils.isEmpty(avatar) || TextUtils.isEmpty(name)) {
            return;
        }
        tvName.setText(name);
        Picasso.with(getContext())
                .load(avatar)
                .resize(UIUtils.dip2px(150), UIUtils.dip2px(70))
                .centerCrop()
                .config(Bitmap.Config.RGB_565)
                .into(ivAvatar);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void helloEventBus(LoginMessage loginMessage) {
        String name = loginMessage.getName();
        String imageUrl = loginMessage.getImageUrl();
        tvName.setText(name);
        Picasso.with(getContext())
                .load(imageUrl)
                .resize(UIUtils.dip2px(60), UIUtils.dip2px(60))
                .centerCrop()
                .config(Bitmap.Config.RGB_565)
                .into(ivAvatar);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
